<template>

	<view class="main">
		<image class="ysa" style="width: 100%;height: 600rpx;position: fixed;top: 0;" src="/static/images/ysa.png"></image>

		<u-navbar :bgColor="bgColor" :fixed="false" title="预约挂号" placeholder="true" @rightClick="rightClick" :autoBack="true"></u-navbar>

		<view class="info">

			<view class="header">
				<view class="row_a_c">
					<view class="xinga"></view>
					<text class="header-title">请填写准确的预约信息</text>
				</view>

				<text class="header-subtitle">（请务必提前填写信息便捷预约）</text>
			</view>

			<!-- 表单部分 -->
			<u--form labelWidth="100" :model="formData" :rules="rules" ref="uForm">
				<!-- 姓名 -->
				<u-form-item label="您的姓名" prop="name">
					<u--input placeholder="请输入姓名" v-model="formData.name"></u--input>
				</u-form-item>

				<!-- 电话 -->
				<u-form-item label="您的电话" prop="phone">
					<u--input placeholder="请输入手机号" v-model="formData.phone" type="number"></u--input>
				</u-form-item>

				<u-form-item label="选择门店" prop="store" @click="mdxz()">
					<u--input placeholder="请选择门店" v-model="formData.storeName"></u--input>
					<u-picker @cancel="showMd=false" :show="showMd" :columns="mDlistData" keyName="name" @confirm="confirmMd"></u-picker>
				</u-form-item>

				<u-form-item label="选择科室" prop="territory" @click="ksxz()">
					<u--input placeholder="请选择科室" v-model="formData.territoryName"></u--input>
					<u-picker @cancel="showKs=false" :show="showKs" :columns="TerritoryData" keyName="name" @confirm="confirmKs"></u-picker>
				</u-form-item>


				<u-form-item label="计划到院时间" prop="arrival_at" @click="showTime=true">
					<u--input placeholder="请选择时间" v-model="formData.arrival_at"></u--input>
					<u-datetime-picker :minDate="currentTimestamp" @cancel="showTime=false" @confirm="confirmTime()" :show="showTime" v-model="valueTime" mode="datetime" :minuteStep="1"></u-datetime-picker>
				</u-form-item>

				<u-form-item label="口腔情况">
					<u--input placeholder="请简述口腔情况" v-model="formData.detail"></u--input>
				</u-form-item>

			</u--form>

			<u-button @click="submit" :custom-style="{ backgroundColor: '#27CCBB', marginTop:'30rpx',color: '#fff', borderRadius: '40rpx', height:'80rpx'}" text="立即预约"></u-button>


		</view>
	</view>

</template>

<script>
	import api_index from '@/api/index.js';

	export default {
		components: {

		},
		async onLoad(option) {
			console.log(uni.$u.config.v);
		},

		async onShow() {
			this.access_token = uni.getStorageSync('access_token_user');

			if (!this.access_token) {
				uni.navigateTo({
					url: '/pages/auth/login'
				});
			} else {
				this.getUserLocation();
			}
		},

		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},


		data() {
			return {
				currentTimestamp: Date.now(), // 当前时间戳（单位：毫秒）
				access_token: null,
				valueTime: Number(new Date()),
				showTime: false,
				showKs: false,
				showMd: false,
				mDlistData: [], //门店列表
				TerritoryData: [], //科室列表
				longitude: 116.33,
				latitude: 40.0,
				rules: {
					name: {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change', 'blur'],
						}
					],


					store: {
						type: 'string',
						required: true,
						message: '请选择门店',
						trigger: ['blur', 'change']
					},
					territory: {
						type: 'string',
						required: true,
						message: '请选择科室',
						trigger: ['blur', 'change']
					},
					arrival_at: {
						type: 'string',
						required: true,
						message: '请计划到院时间',
						trigger: ['blur', 'change']
					},

				},

				bgColor: 'rgba(0, 31, 63, 0)',

				formData: {
					name: '',
					phone: '',
					store: '', //门店ID
					storeName: '', // 显示的门店名称
					territory: '',
					territoryName: '',
					arrival_at: '',
					detail: '',
				},
			};
		},
		methods: {
			//点击门店选择
			mdxz() {
				this.showMd = true;
			},

			ksxz() {
				this.showKs = true;
			},

			confirmMd(e) {
				this.formData.store = e.value[0].id;
				this.formData.storeName = e.value[0].name;
				this.showMd = false;
				this.getStoreTerritoryListFuc();
				this.$refs.uForm.validateField('store', (valid) => {});
			},

			confirmTime(e) {
				const date = new Date(e.value);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				this.formData.arrival_at = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				this.showTime = false;
				this.$refs.uForm.validateField('arrival_at', (valid) => {});
			},





			confirmKs(e) {
				this.formData.territory = e.value[0].id;
				this.formData.territoryName = e.value[0].name;
				this.showKs = false;
				this.$refs.uForm.validateField('territory', (valid) => {});
			},




			//获取门店下科室列表
			async getStoreTerritoryListFuc() {
				var per = {
					store: this.formData.store,
				}
				const res = await api_index.getStoreTerritoryList(per);
				if (res.code == 1) {
					this.$nextTick(() => {
						this.TerritoryData = [res.data.list]
						console.log('获取门店下科室列表', this.TerritoryData)
					});

				} else {
					this.$util.msg(res.message);
					return;
				}
			},

			submit() {
				this.$refs.uForm.validate().then(res => {
					this.addOrderFuc();
				}).catch(errors => {
					uni.$u.toast('请检测填写信息')
				})
			},

			//新增预约
			async addOrderFuc() {
				var per = {
					name: this.formData.name,
					phone: this.formData.phone,
					store: this.formData.store,
					territory: this.formData.territory,
					arrival_at: this.formData.arrival_at,
				}
				if (this.formData.detail) {
					per.detail = this.formData.detail
				}
				const res = await api_index.addOrder(per);
				if (res.code == 1) {
					uni.$u.toast('预约成功')
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}, 1000);
				} else {
					this.$util.msg(res.message);
					return;
				}
			},


			//获取门店列表
			async getStoreListFuc() {
				var per = {
					longitude: this.longitude,
					latitude: this.latitude,
				}
				const res = await api_index.getStoreList(per);
				if (res.code == 1) {

					this.$nextTick(() => {
						this.mDlistData = [res.data.list]
						console.log('获取门店列表', this.mDlistData)
					});

				} else {
					this.$util.msg(res.message);
					return;
				}
			},

			//获取经纬度
			getUserLocation() {
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: (res) => { // 使用箭头函数保持上下文
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						console.log('Latitude:', this.latitude);
						console.log('Longitude:', this.longitude);
						if (this.latitude && this.longitude)
							this.getStoreListFuc();
						this.$nextTick(() => {
							console.log('地图数据更新完成');
						});
					},
					fail: (err) => {
						console.error('获取位置失败', err);
					}
				});
			},



		}
	};
</script>

<style scoped lang="scss">
	.main {}

	.info {
		width: 100%;

		min-height: 1000rpx;
		background: #FFFFFF;
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		position: absolute;

		top: 540rpx;
		padding: 50rpx 32rpx 32rpx 32rpx;
	}


	.form-container {
		padding: 20rpx;
		background-color: #ffffff;
		border-radius: 16rpx;
	}

	.header {
		margin-bottom: 20rpx;
	}

	.xinga {
		width: 6rpx;
		height: 24rpx;
		background: #1FA194;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		margin-right: 10rpx;
		// margin-top: 50rpx;
	}



	.header-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #1CC09B;
	}

	.header-subtitle {
		font-size: 20rpx;
		color: #B2B2B2;
	}

	.add-person {
		font-weight: 400;
		font-size: 24rpx;
		color: #1FA194;
		margin-bottom: 10rpx;
	}

	.add-person-btn {
		margin: 20rpx 0;
		height: 146rpx;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		border: 2rpx dashed #1FA194;
	}

	.add-person-note {
		font-size: 20rpx;
		color: #B2B2B2;
	}

	.yybut {
		width: 622rpx !important;
		height: 180rpx !important;
		background: #27CCBB !important;
		border-radius: 40rpx 40rpx 40rpx 40rpx !important;
	}
</style>